package com.yunquan.ohana.ui.history.status

import android.app.Application
import com.google.gson.Gson
import com.yunquan.ohana.base.bus.event.SingleLiveEvent
import com.yunquan.ohana.base.ui.BaseViewModel
import com.yunquan.ohana.entity.GroupFramesEntity
import com.yunquan.ohana.http.BaseHttp
import com.yunquan.ohana.http.observer.BaseObserver
import com.yunquan.ohana.http.transformer.CommonTransformer
import okhttp3.RequestBody.Companion.toRequestBody

class StatusViewModel(application: Application) : BaseViewModel(application) {

    val ui = SingleLiveEvent<Int>()

    var groupUid: String? = null

    val mData = mutableListOf<GroupFramesEntity>()

    fun getFramesData() {
        if (groupUid == null) return
        val params = mutableMapOf<String, Any>()
        params["groupUid"] = groupUid!!
        val json = Gson().toJson(params)
        val body = json.toRequestBody(BaseHttp.MEDIA_TYPE_JSON)
        BaseHttp.api.getGroupDeviceList(body)
            .compose(CommonTransformer())
            .subscribe(object : BaseObserver<List<GroupFramesEntity>>() {
                override fun onSuccess(result: List<GroupFramesEntity>?) {
                    super.onSuccess(result)
                    mData.clear()
                    result?.let {
                        mData.addAll(it)
                    }
                    mData.sortBy { it.receipt }
                    ui.value = 0
                }
            })
    }
}